<template>
  <div class="report-container-padding">
    <div class="buttonList">
      <el-button @click="handleSaveDraft">保存为草稿</el-button>
      <el-button type="primary" @click="handleSubmit">确认提交</el-button>
    </div>
    <div class="custom-divider"></div>
    <div class="content">
      <div class="left">
        <el-form ref="topicFormRef" :model="formData" :rules="rulesForm">
          <el-form-item label="课题名称：" prop="topicId">
            <el-select-v2
              v-model="formData.topicId"
              filterable
              :options="topicOptions"
              placeholder="请选择"
              clearable
              @change="handleTopicInfo"
            />
          </el-form-item>
        </el-form>
        <el-descriptions
          title="课题信息"
          :column="1"
          class="custom-description"
        >
          <el-descriptions-item
            v-for="item in topicKeys"
            :key="item.key"
            :label="item.label"
          >
            <span>
              {{ topicInfo[item.key] || '' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          title="项目信息"
          :column="1"
          class="custom-description"
        >
          <el-descriptions-item
            v-for="item in projectKeys"
            :key="item.key"
            :label="item.label"
          >
            <span>{{ projectInfo[item.key] || '' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="right">
        <div class="custom-divider-vertical"></div>
        <div class="panel">
          <div class="test-info">
            <div class="display-title">
              <span>试验基本信息</span>
            </div>
            <el-form
              ref="basicFormRef"
              :model="formData"
              :rules="rulesForm"
              label-width="auto"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="试验井位：" prop="wellLocation">
                    <el-select
                      v-model="formData.wellLocation"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in _discStore.getDictType('well_location')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="提供单位：" prop="provideUnit">
                    <el-tree-select
                      v-model="formData.provideUnit"
                      :data="reportingUnitOptions"
                      :render-after-expand="false"
                      placeholder="请选择"
                      filterable
                      clearable
                      check-strictly
                      :props="{
                        value: 'id',
                        label: 'name',
                        children: 'children',
                      }"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="试验井队：" prop="wellTeam">
                    <el-tree-select
                      v-model="formData.wellTeam"
                      :data="reportingUnitOptions"
                      :render-after-expand="false"
                      placeholder="请选择"
                      filterable
                      clearable
                      check-strictly
                      :props="{
                        value: 'id',
                        label: 'name',
                        children: 'children',
                      }"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="井号：" prop="wellNum">
                    <el-input
                      v-model="formData.wellNum"
                      placeholder="请输入"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="试验时间：" prop="experimentDate">
                    <el-date-picker
                      v-model="formData.experimentDate"
                      type="date"
                      placeholder="请选择时间"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <div class="test-info">
            <div class="display-title">
              <span>试验内容</span>
            </div>
            <el-form
              ref="contentFormRef"
              :model="formData"
              :rules="rulesForm"
              label-width="auto"
              label-position="top"
            >
              <el-form-item label="试验过程：" prop="experimentProcess">
                <el-input
                  v-model="formData.experimentProcess"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="试验井段：" prop="experimentWell">
                <el-input
                  v-model="formData.experimentWell"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="施工参数：" prop="constructParameter">
                <el-input
                  v-model="formData.constructParameter"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="试验结果：" prop="experimentResult">
                <el-input
                  v-model="formData.experimentResult"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="预期目的评估：" prop="objEvaluation">
                <el-input
                  v-model="formData.objEvaluation"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="存在问题及损失：" prop="issueLoss">
                <el-input
                  v-model="formData.issueLoss"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="时效数据：" prop="timeData">
                <el-input
                  v-model="formData.timeData"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-form>
          </div>

          <div class="test-info">
            <div class="display-title">
              <span>试验经济损失</span>
            </div>
            <el-form
              ref="lossFormRef"
              :model="formData"
              :rules="rulesForm"
              label-width="auto"
              label-position="top"
            >
              <el-col :span="12">
                <el-form-item label="试验经济损失金额：" prop="lossAmount">
                  <el-input
                    v-model="formData.lossAmount"
                    placeholder="请输入"
                    clearable
                    :formatter="formatter"
                    :parser="parser"
                  >
                    <template #suffix>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-form-item
                label="试验经济损失说明：(费用构成、测算依据等)"
                prop="lossRemark"
              >
                <el-input
                  v-model="formData.lossRemark"
                  :rows="10"
                  type="textarea"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    optionsProps,
    projectInfoProps,
    topicInfoProps,
    filedTestReportProps,
    resTopicListProps,
    resTopicInfoProps,
    resCreateProps,
    resDetailsProps,
    resDrafDetailsProps,
  } from '../interface'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  import { getSimpleDeptList } from '@/api/system/dept'
  import { selectTopicList, queryTopicAndProject } from '@/api/project/index'
  import {
    getFieldTestDetails,
    saveFieldTestCreate,
  } from '@/api/project/researchFunds'
  import { useDepartmentTree, DepartmentNode } from '@/utils/useDepartmentTree'
  import { useDictStore } from '@/store/modules/dict'
  import { useTimeFormat } from '@/utils/useTimeFormat'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const _discStore = useDictStore()
  const { closeTabNavigate } = useCloseTabNavigate()
  const { updateTime } = useTimeFormat()
  const route = useRoute()
  // 课题信息映射
  const topicKeys = [
    { label: '课题名称：', key: 'name' },
    { label: '课题类型：', key: 'type' },
    { label: '课题负责人：', key: 'leader' },
    { label: '专业领域：', key: 'subjectAreaText' },
    { label: '研究周期：', key: 'researchStartDate' },
    { label: '预计投入经费：', key: 'estimatedBudget' },
    { label: '是否需要外协：', key: 'externalCooperationRequired' },
    { label: '承担单位：', key: 'leadingUnitName' },
    { label: '协作单位：', key: 'collaboratingUnitName' },
  ]
  // 项目信息映射
  const projectKeys = [
    { label: '项目编号：', key: 'projectCode' },
    { label: '项目名称：', key: 'projectName' },
    { label: '项目等级：', key: 'projectLevel' },
    { label: '项目类型：', key: 'projectTypeName' },
    { label: '是否重点项目：', key: 'keyProject' },
    { label: '项目负责人：', key: 'headerName' },
  ]

  // 课题信息
  const topicInfo = reactive<Partial<topicInfoProps>>({})
  // 项目信息
  const projectInfo = reactive<Partial<projectInfoProps>>({})

  // 课题下拉框
  const topicOptions = ref<optionsProps[]>([])

  const topicFormRef = ref<FormInstance>()
  const basicFormRef = ref<FormInstance>()
  const contentFormRef = ref<FormInstance>()
  const lossFormRef = ref<FormInstance>()
  const rulesForm = reactive<FormRules<filedTestReportProps>>({
    topicId: [{ required: true, message: '请选择课题名称', trigger: 'change' }],
    wellLocation: [
      { required: true, message: '请选择试验井位', trigger: 'change' },
    ],
    provideUnit: [
      { required: true, message: '请选择提供单位', trigger: 'change' },
    ],
    wellTeam: [
      { required: true, message: '请选择试验井队', trigger: 'change' },
    ],
    wellNum: [{ required: true, message: '请输入井号', trigger: 'blur' }],
    experimentDate: [
      { required: true, message: '请选择试验时间', trigger: 'change' },
    ],
    experimentProcess: [
      { required: true, message: '请输入试验过程', trigger: 'blur' },
    ],
    experimentWell: [
      { required: true, message: '请输入试验井段', trigger: 'blur' },
    ],
    constructParameter: [
      { required: true, message: '请输入施工参数', trigger: 'blur' },
    ],
    experimentResult: [
      { required: true, message: '请输入试验结果', trigger: 'blur' },
    ],
    objEvaluation: [
      { required: true, message: '请输入预期目的评估', trigger: 'blur' },
    ],
    issueLoss: [
      { required: true, message: '请输入存在问题及损失', trigger: 'blur' },
    ],
    timeData: [{ required: true, message: '请输入时效数据', trigger: 'blur' }],
    lossAmount: [
      { required: true, message: '请输入试验经济损失金额', trigger: 'blur' },
    ],
    lossRemark: [
      { required: true, message: '请输入试验经济损失说明', trigger: 'blur' },
    ],
  })
  // 表单信息
  const formData = reactive<Partial<filedTestReportProps>>({})
  const formatter = (value: string) => {
    if (!value) {
      return null
    }
    // 保留最多两位小数的正则表达式
    return value.replace(/^(0|[1-9]\d*)(\.\d{0,2})?/, (match) => match)
  }

  const parser = (value: string) => {
    if (!value) {
      return null
    }
    // 确保第一位不能是小数点
    if (value.startsWith('.')) {
      return null
    }
    return (
      value
        .replace(/[^0-9.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        // eslint-disable-next-line no-useless-escape
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    )
  }
  // 校验
  const validateForm = (
    formRef: FormInstance | undefined
  ): Promise<boolean> => {
    return new Promise((resolve) => {
      if (!formRef) return resolve(false)
      formRef.validate((valid) => {
        resolve(valid)
      })
    })
  }
  // 草稿
  const handleSaveDraft = async () => {
    try {
      const params = {
        id: route.query?.id || '',
        type: 'FIELD_EXPERIMENT_FUNDING',
        submitJson: JSON.stringify({
          ...formData,
          draftBoxId: route.query?.id || '',
        }),
      }
      const res: resCreateProps = await postDraftBoxCreate(params)
      if (res && res.code === 0) {
        ElMessage.success('保存现场试验经费草稿成功')
        closeTabNavigate()
      } else {
        ElMessage.error(`保存现场试验经费草稿失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('保存现场试验经费草稿失败', e)
    }
  }
  // 提交
  const handleSubmit = async () => {
    const [topicValid, basicValid, contentValid, lossValid] = await Promise.all(
      [
        validateForm(topicFormRef.value),
        validateForm(basicFormRef.value),
        validateForm(contentFormRef.value),
        validateForm(lossFormRef.value),
      ]
    )
    if (topicValid && basicValid && contentValid && lossValid) {
      // 提交逻辑
      try {
        const params = {
          ...formData,
          draftBoxId: route.query?.id || '',
        }
        const res: resCreateProps = await saveFieldTestCreate(params)
        if (res && res.code === 0) {
          ElMessage.success('创建现场试验经费成功')
          closeTabNavigate({ name: 'ResearchFunds_FieldTest' })
        } else {
          ElMessage.error(`创建现场试验经费失败: ${res.msg || '未知错误'}`)
        }
      } catch (e) {
        console.error('创建现场试验经费失败', e)
      }
    } else {
      console.error('表单校验未通过')
    }
  }

  // 处理项目 课题信息
  const handleTopicInfo = async (value: number | string) => {
    try {
      const params = {
        topicId: value,
      }
      const res: resTopicInfoProps = await queryTopicAndProject(params)
      if (res && res.code === 0) {
        Object.assign(topicInfo, res.data.topicRespVO)
        topicInfo.type = _discStore.getDictLabelForValue(
          'topic_type',
          res.data.topicRespVO.type
        )
        topicInfo.externalCooperationRequired = _discStore.getDictLabelForValue(
          'yes_no',
          res.data.topicRespVO.externalCooperationRequired
        )
        topicInfo.researchStartDate = `${updateTime(res.data.topicRespVO.researchStartDate, 'YYYY-MM-DD') || ''} 至 ${updateTime(res.data.topicRespVO.researchEndDate, 'YYYY-MM-DD') || ''}`

        Object.assign(projectInfo, res.data.projectInfoRespVO)
        projectInfo.keyProject = _discStore.getDictLabelForValue(
          'yes_no',
          res.data.projectInfoRespVO.keyProject
        )
        projectInfo.projectLevel = _discStore.getDictLabelForValue(
          'project_level',
          res.data.projectInfoRespVO.projectLevel
        )
        projectInfo.projectType = _discStore.getDictLabelForValue(
          'project_level',
          res.data.projectInfoRespVO.projectType
        )
      }
    } catch (e) {
      console.error('获取课题详细信息失败', e)
    }
  }

  // 获取课题名称列
  const getTopicList = async () => {
    try {
      const res: resTopicListProps = await selectTopicList({ type: 1 })
      if (res && res.code === 0 && res.data) {
        topicOptions.value = res.data?.map((item) => {
          return {
            id: item.topicId,
            label: item.topicName,
            value: item.topicId,
          }
        })
      } else {
        console.warn('未获取到课题名称明细')
      }
    } catch (e) {
      console.error('获取课题名称明细时出错:', e)
    }
  }

  // 提出单位下拉框
  const reportingUnitOptions = ref<DepartmentNode[]>([])
  const handleDeptDetails = async () => {
    try {
      const res: any = await getSimpleDeptList()
      if (res && res.code === 0 && res.data) {
        reportingUnitOptions.value = useDepartmentTree(res.data || [])
      }
    } catch (e) {
      console.error('获取上报单位出错:', e)
    }
  }

  // 获得明细  当从草稿中进入时
  const fetchDetails = async () => {
    try {
      const res: resDrafDetailsProps = await getFieldTestDetails({
        id: route.query?.id || '',
        getType: 1,
      })
      if (res && res.code === 0 && res.data) {
        Object.assign(formData, res.data)
        handleTopicInfo(formData.topicId)
      } else {
        ElMessage.error(`获取公司年度预算失败: ${res?.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('获取公司年度预算详情失败', e)
    }
  }

  onMounted(async () => {
    await Promise.all([getTopicList(), handleDeptDetails()])
    if (route.query?.getType === '1') {
      fetchDetails()
    }
  })
</script>

<style lang="scss" scoped>
  .report-container-padding {
    display: flex;
    flex-direction: column;
    .buttonList {
      display: flex;
      align-items: center;
      justify-content: end;
    }

    .custom-divider {
      position: relative;
      height: 1px;
      margin: 20px 0;
      background-color: #edeff2;

      &::before {
        position: absolute;
        top: 0;
        right: -20px;
        left: -20px;
        height: 1px;
        content: '';
        background-color: #edeff2;
      }
    }

    .custom-divider-vertical {
      position: relative;
      width: 1px;
      height: 100%; /* 你可以根据需要调整高度 */
      margin: 0 20px 0 0;
      background-color: #edeff2;
      &::before {
        position: absolute;
        top: -20px; /* 你可以根据需要调整上下边距 */
        bottom: -20px; /* 你可以根据需要调整上下边距 */
        left: 0;
        width: 1px;
        content: '';
        background-color: #edeff2;
      }
    }
    .content {
      display: flex;
      flex-grow: 1;
    }
    .left {
      width: 423px;
      height: 100%;
      padding: 0 20px 0 0;
    }
    .right {
      display: flex;
      width: calc(100% - 423px);

      .panel {
        width: 100%;
      }
      .test-info {
        width: 100%;
        margin-bottom: 20px;
      }

      .display-title {
        height: 28px;
        padding-left: 12px;
        margin-bottom: 20px;
        font-size: 14px;
        font-weight: 500;
        line-height: 28px;
        color: #606266;
        background: #f7f8f9;
        border-left: 5px solid #1890ff;
        border-radius: 2px;
      }
    }

    :deep(.custom-description) {
      margin-top: 20px;

      .el-descriptions__header {
        background: #f7f8f9;
        .el-descriptions__title {
          padding: 3px 0 3px 10px;
          font-size: 14px;
          font-weight: 400;
          line-height: 22px;
          color: #606266;
          border: none;
        }
      }

      .el-descriptions__table tr:last-child .el-descriptions__cell {
        padding-bottom: 0 !important;
      }

      .el-descriptions__cell {
        padding-bottom: 10px !important;
        font-size: 12px;
        font-weight: 400;
        line-height: 17px;
      }
      .el-descriptions__label {
        display: inline-block;
        width: 84px; /* 根据需要调整宽度 */
        margin-right: 10px !important;
        color: #00000040;
        text-align: right;
      }

      .el-descriptions__content {
        position: relative;
        display: inline-flex;
        max-width: 192px;
        span {
          position: relative; /* 为伪元素定位 */
          overflow: hidden; /* 隐藏超出部分 */
          text-overflow: ellipsis;
          white-space: nowrap; /* 防止内容换行 */
        }
      }
    }
  }
</style>
